import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { DatePipe } from '@angular/common';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { CommonService } from '../../../../services-common/common.service';
import { SecondCouponService } from '../services/second-coupon.service';
import { SecondDescentService } from '../services/second-descent.service';

@Component({
  selector: 'app-second-descent-edit',
  templateUrl: './second-descent-edit.component.html',
  styleUrls: ['./second-descent-edit.component.scss'],
  providers: [DatePipe]
})
export class SecondDescentEditComponent implements OnInit {

  routeParams: any = {};
  formParams: any = {
    status: 5, // 状态 1、未开始 2、进行中 3、已结束 4、已停止 5 草稿 6、待审核 7、审核不通过 8删除
    type: 1, // 活动类型：1、满减型 2、折扣型 3、多件折扣 4、多件立减 5、阶梯满减 6、阶梯折扣
    name: '', // 活动名称
    showCopy: '', // 活动标题
    remark: '', // 备注
    orderLimitMoney: '', // 优惠门槛
    limitSmall: '', // 减免额度 | 折扣力度
    overlayFlag: '', // 倍数减免 0：否，1：是
    limitBig: '', // 最高减免金额

    userType: 0, // 参与人限制 | 适用用户(0-通用、1-C端、2-B端)
    beginTime: '', // 活动生效开始时间
    endTime: '', // 活动生效结束时间
    isPlusCoupons: '0', // 是否可以叠加优惠券(0是 1否)
    skinTopImage: '', // 顶部图片--- wap
    // skinTopMargin: 0, // 顶部边距--- wap
    skinBgColor: '#FFFFFF', // 背景色--- wap
    skinTopImagePc: '', // 顶部图片 pc端
    // skinTopMarginPc: 0, // 顶部边距 pc端
    skinBgColorPc: '#FFFFFF', // 背景色 pc端
    isFilterSort: '', // 筛选排序 0-不开启 1-开启

    // containsTypes: '', // 品牌list 0：为全部 -1：为全不选
    // containsSeries: '', // 系列list 0：为全部 -1：为全不选
    containsModel: '', // 机型list 0：为全部 -1：为全不选
    containsSupplier: '', // 货主list 0：为全部 -1：为全不选
    containsColourB: '', // B端成色list 0：为全部 -1：为全不选
    containsColourC: '', // C端成色list 0：为全部 -1：为全不选
    filterGoods: '', // 排除商品list 0：为全部
    containsGoods: '', // 追加商品list 0：为全部
  };

  takeEffectDates: any[] = []; // 活动生效时间
  discountTable: any = []; // 多件折扣Table
  couponOverlay: boolean = true; // 优惠券叠加

  /**
   * 适用商品
   * ----------------------------------------------------------------
   */

  supplierOptions: any = []; // 供应商 | 货主
  supplierSelected: any = []; // 供应商 | 货主
 
  modelAll: boolean = false; // 机型全选
  supplierAll: boolean = false; // 货主全选
 
  // 成色B端 options
  conditionOptionsB: any = [];
  selectConditionB: any = [];
 
  // 成色C端 options
  conditionOptionsC: any = [];
  selectConditionC: any = [];
 
  // 选择指定机型
  isModelVisible = false;
  defaultModelKeys: any[] = [];
 
  // 指定商品勾选 Modal
  modalGoodsType: number = 1; // 1：排除可用 2：追加可用
  isGoodsVisible = false;
  modelGoodOptions: any = [];
  disabledOptions: any = [];
 
  excludeGoodsIds: any = []; // 排除可用ids
  addGoodsIds: any = []; // 追加可用ids
 
  // 查看已选商品 Modal
  isPreviewVisible = false;
  previewGoodIds: any = [];
  previewTable: any = [];
 
  // 审核 Modal
  isExamineVisible = false;
  examineParams = {
    remark: ''
  };

  constructor(
    private message: NzMessageService,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private modal: NzModalService,
    private secondCouponService: SecondCouponService,
    private services: SecondDescentService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    if (['1', '3'].includes(this.routeParams.type)) {
      this.loadDetails();
    } else {
      this.loadSupplierOptions();
      this.initconditionDatas();
    }
  }

  async loadDetails() {
    await this.loadSupplierOptions();
    await this.initconditionDatas();

    let params = {
      id: this.routeParams.id,
      page: 1,
      pageSize: 10
    }
    const messId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const { code, data, message }: any = await this.services.getDescentDetail(params);
    this.message.remove(messId);

    if (code === 0) {
      const { promotionInfo } = data || {};
      
      this.formParams.status = promotionInfo.status; // 状态
      this.formParams.type = promotionInfo.type; // 类型
      this.formParams.name = promotionInfo.name; // 活动名称
      this.formParams.showCopy = promotionInfo.showCopy; // 活动标题
      this.formParams.remark = promotionInfo.remark || ''; // 备注

      this.formParams.orderLimitMoney = promotionInfo.orderLimitMoney || ''; // 优惠门槛
      this.formParams.limitSmall = promotionInfo.limitSmall || ''; // 减免额度 | 折扣力度
      this.formParams.overlayFlag = this.isEmpty(promotionInfo.overlayFlag) ? '' : String(promotionInfo.overlayFlag); // 倍数减免
      this.formParams.limitBig = promotionInfo.limitBig || ''; // 最高减免金额
      this.discountTable = this.isEmpty(promotionInfo.discountContent) ? [] : JSON.parse(promotionInfo.discountContent); // 多件折扣

      this.formParams.userType = promotionInfo.userType; // 参与人限制
      this.formParams.beginTime = promotionInfo.beginTime || ''; // 活动生效开始时间
      this.formParams.endTime = promotionInfo.endTime || ''; // 活动生效结束时间
      this.takeEffectDates = [promotionInfo.beginTime, promotionInfo.endTime]; // 活动生效时间
      this.formParams.isPlusCoupons = promotionInfo.isPlusCoupons; // 是否可以叠加优惠券
      this.couponOverlay = promotionInfo.isPlusCoupons == '0' ? true : false; // 优惠券叠加Check

      this.formParams.skinTopImage = promotionInfo.skinTopImage; // 顶部图片 wap
      this.formParams.skinBgColor = promotionInfo.skinBgColor; // 背景色 wap
      this.formParams.skinTopImagePc = promotionInfo.skinTopImagePc; // 顶部图片 pc
      this.formParams.skinBgColorPc = promotionInfo.skinBgColorPc; // 背景色 pc
      this.formParams.isFilterSort = !this.commonService.isEmpty(promotionInfo.isFilterSort) ? promotionInfo.isFilterSort : ''; // 筛选排序

      // 指定机型
      switch (promotionInfo.containsModel) {
        case '0':
          this.modelAll = true;
          break;
        case '-1':
          this.modelAll = false;
          break;
        default:
          this.modelAll = false;
          break;
      }
      // this.formParams.containsTypes = promotionInfo.containsTypes;
      // this.formParams.containsSeries = promotionInfo.containsSeries;
      this.formParams.containsModel = promotionInfo.containsModel;
      // let brandArr = ['0', '-1'].includes(promotionInfo.containsTypes) ? [] : promotionInfo.containsTypes.split(',');
      // let seriesArr = ['0', '-1'].includes(promotionInfo.containsSeries) ? [] : promotionInfo.containsSeries.split(',');
      let modelArr = ['0', '-1'].includes(promotionInfo.containsModel) ? [] : promotionInfo.containsModel.split(',');
      this.defaultModelKeys = [...modelArr];

      // 货主
      if (promotionInfo.containsSupplier === '-1') {
        this.supplierAll = false;
        this.supplierSelected = [];
      } else {
        let tempSuppList = promotionInfo.containsSupplier.split(',').map((m: any) => +m);
        if (tempSuppList.length === this.supplierOptions.length) {
          this.supplierAll = true;
        } else {
          this.supplierAll = false;
        }
        this.supplierSelected = tempSuppList;
      }
      
      // B端成色
      if (promotionInfo.containsColourB === '0') {
        this.selectConditionB = this.conditionOptionsB.map((item: any) => item.id);
      } else if (promotionInfo.containsColourB === '-1') {
        this.selectConditionB = [];
      } else {
        this.selectConditionB = promotionInfo.containsColourB.split(',').map((m: any) => +m);
      }

      // C端成色
      if (promotionInfo.containsColourC === '0') {
        this.selectConditionC = this.conditionOptionsC.map((item: any) => item.id);
      } else if (promotionInfo.containsColourB === '-1') {
        this.selectConditionC = [];
      } else {
        this.selectConditionC = promotionInfo.containsColourC.split(',').map((m: any) => +m);
      }
      
      this.formParams.filterGoods = promotionInfo.filterGoods; // 排除商品
      this.excludeGoodsIds = (promotionInfo.filterGoods && promotionInfo.filterGoods != '0') ? promotionInfo.filterGoods.split(',') : []; // 排除商品Ids
      this.formParams.containsGoods = promotionInfo.containsGoods; // 追加商品
      this.addGoodsIds = (promotionInfo.containsGoods && promotionInfo.containsGoods != '0') ? promotionInfo.containsGoods.split(',') : []; // 追加商品商品Ids
    } else {
      this.message.error(message);
    }
  }

  // 查询供应商 | 货主
  async loadSupplierOptions() {
    const { code, message, data }: any = await this.secondCouponService.querySupplierList();
    if (code === 0) {
      this.supplierOptions = data.records.length ? data.records.filter((item: any) => item.name) : [];
      this.supplierOptions.unshift({
        id: 0,
        name: '自营'
      })
    } else {
      this.message.error(message);
    }
  }

  // 成色options
  async initconditionDatas() {
    this.conditionOptionsB = await this.commonService.getDictList('machine_condition_b');
    this.conditionOptionsC = await this.commonService.getDictList('machine_condition');
  }

  /**
   * ----------------------------------------------------------------
   * 多件折扣 or 多件立减
   * ----------------------------------------------------------------
   */
  addDiscountItem() {
    if (this.verifDiscountTable(this.formParams.type)) {
      this.message.warning('优惠内容已添加项中存在未填写项，请先完善信息');
      return
    }
    if (this.discountTable.length < 5) {
      // (多件折扣:3 & 阶梯折扣:6) | (多件立减:4 & 阶梯满减:5)
      const objs: any = {
        3: {number: '', discountRate: '', maxReduction: ''},
        4: {number: '', reduction: ''},
        5: {orderLimitMoney: '', reduction: ''},
        6: {orderLimitMoney: '', discountRate: '', maxReduction: ''}
      }
      this.discountTable = [
        ...this.discountTable,
        objs[this.formParams.type]
      ]
    }
  }
  
  deleteDiscountItem(index: number) {
    this.discountTable = this.discountTable.filter((d: any, i: number) => i !== index);
  }

  // 判断对象是否存在空值
  judgeObjNullValue(obj: any) {
    let flag = false;
    for (let key in obj) {
      if (this.commonService.isEmpty(obj[key])) {
        flag = true;
      }
    }

    return flag;
  }

  verifDiscountTable(type: number) {
    // (多件折扣:3 & 阶梯折扣:6) | (多件立减:4 & 阶梯满减:5)
    let tempBool = this.discountTable.some((item: any) => {
      return this.judgeObjNullValue(item)
    })

    return tempBool;
  }

  limitMinInput(index: number) {
    let minNum = 1;
    if (this.discountTable.length > 1 && index !== 0) {
      // 注: keyStr 件数 和 金额 字段不同
      let keyStr = [3, 4].includes(this.formParams.type) ? 'number' : 'orderLimitMoney';
      let preNum = this.discountTable[index - 1][keyStr];
      minNum = preNum ? preNum + 1 : 1;
    }
    return minNum;
  }

  limitMaxInput(index: number) {
    let maxNum = Infinity;
    if (this.discountTable.length > 1 && index !== this.discountTable.length - 1) {
      // 注: keyStr 件数 和 金额 字段不同
      let keyStr = [3, 4].includes(this.formParams.type) ? 'number' : 'orderLimitMoney';
      let nextNum = this.discountTable[index + 1][keyStr];
      maxNum = nextNum ? nextNum - 1 : Infinity;
    }
    return maxNum;
  }

  /**
   * ----------------------------------------------------------------
   * 指定机型 Modal Select Tree
   * ----------------------------------------------------------------
   */
  selectMoreModel() {
    this.defaultModelKeys = [];
    this.defaultModelKeys = this.mergeTreeKey();
    this.isModelVisible = true;
  }

  subModelTree(objs: any) {
    // this.formParams.containsTypes = objs.brandList.join(',');
    // this.formParams.containsSeries = objs.seriesList.join(',');
    this.formParams.containsModel = objs.modelList.join(',');
    this.defaultModelKeys = this.mergeTreeKey();
    if (this.defaultModelKeys.length) {
      this.modelAll = false;
    }
  }

  mergeTreeKey() {
    // let brandArr = this.formParams.containsTypes ? this.formParams.containsTypes.split(',') : [];
    // let seriesArr = this.formParams.containsSeries ? this.formParams.containsSeries.split(',') : [];
    let modelArr = (this.formParams.containsModel && this.formParams.containsModel != '0') ? this.formParams.containsModel.split(',') : [];
    return [...modelArr].map((item: any) => +item);
  }

  /**
   * ----------------------------------------------------------------
   * 商品选择 Modal Table
   * ----------------------------------------------------------------
   */
  showSelectGoods(type: number) {
    // type 1：排除可用 2：追加可用
    if (type === 1) {
      this.modelGoodOptions = this.excludeGoodsIds;
      this.disabledOptions = this.addGoodsIds;
    } else {
      this.modelGoodOptions = this.addGoodsIds;
      this.disabledOptions = this.excludeGoodsIds;
    }
    this.modalGoodsType = type;
    this.isGoodsVisible = true;
  }

  submitSelectGoods(obj: any) {
    // 1：排除可用 2：追加可用
    if (this.modalGoodsType === 1) {
      this.excludeGoodsIds = obj.ids;
    } else {
      this.addGoodsIds = obj.ids;
    }
  }

  /**
   * ----------------------------------------------------------------
   * 勾选预览 Modal Table
   * ----------------------------------------------------------------
   */
  previewModal(type: number) {
    if (type === 1) {
      this.previewGoodIds = this.excludeGoodsIds;
    } else {
      this.previewGoodIds = this.addGoodsIds;
    }
    this.isPreviewVisible = true;
  }

  addExcludeChange(result: Array<any>) {
    this.modelGoodOptions = [...result];
  }

  // params handle 0：为全部 -1：为全不选
  paramHandle(state: boolean, result: any) {
    let tempStr = '';
    if (state) {
      tempStr = '0';
    } else if (!state && !result.length) {
      tempStr = '-1';
    } else {
      if (Object.prototype.toString.call(result) === '[object Array]') {
        tempStr = result.join(',');
      } else {
        tempStr = result;
      }
    }
    return tempStr;
  }

  /**
   * ----------------------------------------------------------------
   * 发布 | 保存
   * ----------------------------------------------------------------
   */

  subRelease() {
    if (!this.isVerifForms()) {
      return
    }
    this.modal.confirm({
      nzTitle: '<i>提示</i>',
      nzContent: '<b>确认发布?</b>',
      nzOnOk: () => {
        this.submitForms(0);
      }
    });
  }
  
  async submitForms(type: number) {
    if (!this.isVerifForms()) {
      return
    }
    // 发布状态为未开始1；新增 | 复制 状态为草稿5
    if (type === 0) {
      this.formParams.status = 1;
    } else {
      if (['0', '3'].includes(this.routeParams.type)) {
        this.formParams.status = 5;
      }
    }
    let params = {
      ...this.formParams,
      discountContent: this.discountTable.length ? JSON.stringify(this.discountTable) : '', // 多件折扣Table
      isPlusCoupons: this.couponOverlay ? '0' : '1', // 优惠券叠加
      orderLimitMoney: this.isEmpty(this.formParams.orderLimitMoney) ? '0' : this.formParams.orderLimitMoney,
      limitSmall: this.isEmpty(this.formParams.limitSmall) ? '0' : this.formParams.limitSmall,
      limitBig: this.isEmpty(this.formParams.limitBig) ? '0' : this.formParams.limitBig,
      // containsTypes: this.paramHandle(this.modelAll, this.formParams.containsTypes), // 品牌
      // containsSeries: this.paramHandle(this.modelAll, this.formParams.containsSeries), // 系列
      containsModel: this.paramHandle(this.modelAll, this.formParams.containsModel), // 机型
      containsSupplier: (!this.supplierAll && !this.supplierSelected.length) ? '-1' : this.supplierSelected.join(','), // 货主
      isSup: this.supplierAll ? 0 : 1, // 0全选 1不全选(后端判断可用商品使用)
      containsColourB: this.selectConditionB.length === 0 ? -1 : this.selectConditionB.length === this.conditionOptionsB.length ? 0 : this.selectConditionB.join(','),
      containsColourC: this.selectConditionC.length === 0 ? -1 : this.selectConditionC.length === this.conditionOptionsC.length ? 0 : this.selectConditionC.join(','),
      filterGoods: this.excludeGoodsIds.length ? this.excludeGoodsIds.join(',') : '0', // 排除商品
      containsGoods: this.addGoodsIds.length ? this.addGoodsIds.join(',') : '0' // 追加商品
    }
    // return
    let res: any;
    if (['0', '3'].includes(this.routeParams.type)) {
      res = await this.services.addDescentItem(params);
    } else {
      params.id = this.routeParams.id;
      res = await this.services.updateDescentItem(params);
    }
    
    if (res.code === 0) {
      this.message.success('操作成功');
      this.back();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 验证
   * ----------------------------------------------------------------
   */
  isVerifForms() {
    if (this.isEmpty(this.formParams.name)) {
      this.message.warning('请输入活动名称');
      return false;
    } else if (this.isEmpty(this.formParams.showCopy)) {
      this.message.warning('请输入活动标题');
      return false;
    } else if (this.formParams.type === 1 && this.isEmpty(this.formParams.orderLimitMoney)) {
      // ------ 满减 1 ------
      this.message.warning('请输入优惠门槛');
      return false;
    } else if (this.formParams.type === 1 && this.isEmpty(this.formParams.limitSmall)) {
      // ------ 满减 1 ------
      this.message.warning('请输入减免额度');
      return false;
    } else if (this.formParams.type === 1 && this.isEmpty(this.formParams.overlayFlag)) {
      // ------ 满减 1 ------
      this.message.warning('请选择倍数减免');
      return false;
    } else if (this.formParams.type === 2 && this.isEmpty(this.formParams.orderLimitMoney)) {
      // ------ 折扣 2 ------
      this.message.warning('请输入优惠门槛');
      return false;
    } else if (this.formParams.type === 2 && this.isEmpty(this.formParams.limitSmall)) {
      // ------ 折扣 2 ------
      this.message.warning('请输入折扣力度');
      return false;
    } else if (this.formParams.type === 2 &&this.isEmpty(this.formParams.limitBig)) {
      // ------ 折扣 2 ------
      this.message.warning('请输入最高减免金额');
      return false;
    } else if ([3, 4, 5, 6].includes(this.formParams.type) && !this.discountTable.length) {
      this.message.warning('请先添加优惠内容');
      return false;
    } else if ([3, 4, 5, 6].includes(this.formParams.type) && this.verifDiscountTable(this.formParams.type)) {
      this.message.warning('优惠内容存在未填写项');
      return false;
    } else if (!this.takeEffectDates.length) {
      this.message.warning('请输入活动生效时间');
      return false;
    } else if (!this.formParams.skinBgColor) {
      this.message.warning('请输入手机端背景色');
      return false;
    } else if (!this.formParams.skinTopImage) {
      this.message.warning('请选择手机端顶部图片');
      return false;
    } else if (!this.formParams.skinTopImagePc) {
      this.message.warning('请选择PC端背景色');
      return false;
    } else if (!this.formParams.skinBgColorPc) {
      this.message.warning('请选择PC端顶部图片');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.isFilterSort)) {
      this.message.warning('请选择筛选排序');
      return false;
    } else {
      return true;
    }
  }

  // 优惠门槛 | 减免额度验证
  discountLimitChange(num: number) {
    if (
      this.formParams.orderLimitMoney &&
      this.formParams.limitSmall &&
      this.formParams.orderLimitMoney <= this.formParams.limitSmall
    ) {
      switch (num) {
        case 0:
          // console.log('优惠门槛');
          this.message.warning('优惠门槛值需大于减免额度值');
          this.formParams.orderLimitMoney = '';
          return
        case 1:
          // console.log('减免额度');
          this.message.warning('减免额度值需小于优惠门槛值');
          this.formParams.limitSmall = '';
          return
      }
    }
  }

  /**
   * ----------------------------------------------------------------
   * 组件操作
   * ----------------------------------------------------------------
   */

  // 券类type change
  couponTypeChange(event: number) {
    this.formParams.limitSmall = '' // 减免额度 | 折扣力度
    this.formParams.overlayFlag = '' // 倍数减免 0：否，1：是
    this.formParams.limitBig = '' // 最高减免金额
    this.discountTable = []; // 多件折扣Table
    this.formParams.orderLimitMoney = ''; // 优惠门槛

    if (event === 3) {
      this.formParams.orderLimitMoney = '0'; // 优惠门槛
    }
  }

  // 日期选择change
  onDateChange(result: any[], keyArrs: Array<string>) {
    this.formParams[keyArrs[0]] = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd HH:mm:ss') : '';
    this.formParams[keyArrs[1]] = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd HH:mm:ss') : '';
  }

  /**
   * 机型 | 货主全选 Change
   * @param val 
   * @param type 1：机型 2：货主
   */
  modelOwnerAllChange(val: any, type: number) {
    switch (type) {
      case 1:
        this.formParams.containsModel = '';
        this.defaultModelKeys = [];
        break;
      case 2:
        this.supplierSelected = this.supplierOptions.map((item: any) => item.id);
        break;
    }
  }

  /**
   * 机型 | 货主 ** 全不选 **
   * @param type 1：机型 2：货主
   */
  modelOwnerNotAllChange(type: number) {
    switch (type) {
      case 1:
        this.modelAll = false;
        this.formParams.containsModel = '';
        this.defaultModelKeys = [];
        break;
      case 2:
        this.supplierAll = false;
        this.supplierSelected = [];
        break;
    }
  }

  // 货主 select change
  supplierChange(val: any) {
    if (!val.length || val.length !== this.supplierOptions.length) {
      this.supplierAll = false;
    } else if (val.length === this.supplierOptions.length) {
      this.supplierAll = true;
    }
  }

  // is Empty
  isEmpty(val: any) {
    if (val === '' || val === undefined || val === null) {
      return true;
    } else {
      return false;
    }
  }

  // back
  back() {
    history.back();
  }
}
